﻿namespace IBTrader.Model
{
    using IBTrader.Frontend;
    using IBTrader.Modules.Market;
    using IBTrader.Modules.Tws;
    using System;
    using System.Linq;
    using System.Windows;

    public class AlgoOrders : NotifyPropertyChanged
    {
        private Algo algo;
        private double lastSumm;
        private string lastSummary;
        private DateTime lastSummaryTick = DateTime.Now;
        internal int Total, Bought, Sold;
        public Orders Filled { get; private set; }

        internal AlgoOrders(Algo algo)
        {
            this.algo = algo;
            Filled = new Orders();
        }
        internal void StatusChanged(Order order)
        {
            if (Application.Current == null) return; // Console mode
            if (order.Algo != algo) return;
            var filled = order.Status == OrderStatus.Filled;
            var contains = Filled.Contains(order);
            // TODO: ?
            if (filled && !contains) Application.Current.Dispatcher.Invoke((Action<Order>)Filled.Add, order);
            if (!filled && contains) Application.Current.Dispatcher.Invoke((Func<Order, bool>)Filled.Remove, order);
            //if (filled && !contains) Filled.Add(order);
            //if (!filled && contains) Filled.Remove(order);
            Changed(() => Summary);
        }
        internal void FilledChanged(Order order, int newFilled)
        {
            if (order.Algo != algo) return;
            var diff = newFilled - order.Filled;
            Total += diff;
            if (order.Action == OrderAction.BUY)
                Bought += diff;
            if (order.Action == OrderAction.SELL)
                Sold += diff;
        }
        internal void UpdateSummary()
        {
            lastSummaryTick = DateTime.MinValue;
            Changed(() => Summary);
        }
        public string Summary
        {
            get
            {
                if (DateTime.Now > lastSummaryTick)
                {
                    lastSummaryTick = DateTime.Now.AddSeconds(3);
                    var bought = Filled.Where(o => o.Action == OrderAction.BUY);
                    var sold = Filled.Where(o => o.Action == OrderAction.SELL);
                    Func<Order, double> summ = o => o.Filled * o.FillPrice;
                    if (bought.Count() == sold.Count())
                        lastSumm = sold.Select(summ).Sum() - bought.Select(summ).Sum();
                    lastSummary = string.Format("Filled {1}, Bought {2}, Sold {3}, Summ {4:0.000}", 0, Total, Bought, Sold, lastSumm);
                }
                return lastSummary;
            }
        }

        internal void Clear()
        {
            Total = Bought = Sold = 0;
            Filled.Clear();
            UpdateSummary();
        }
    }
}